import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
import App from './App.vue'
import VueRouter from "vue-router";
import route from './router/router'
//省市区插件
import VDistpicker from 'v-distpicker'

//导入axios
import axios from 'axios'

Vue.prototype.$http = axios;


//开启debug模式
Vue.config.debug = true;

Vue.use(VueRouter);

Vue.use(ElementUI)

//省市区插件
Vue.component('v-distpicker', VDistpicker)


//自定义  cookie操作
Vue.prototype.setCookie = (c_name, value, expiredays) => {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

//获取cookie、
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return (arr[2]);
    else
        return null;
}
Vue.prototype.getCookie = getCookie;

//删除cookie
Vue.prototype.delCookie =(name) => {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

function logout(){
    //删除cookie并跳到登录页

    //成功后删除cookie
    this.delCookie('token');
    //跳转到登录页
    this.$router.push('/login');
}
Vue.prototype.logout = logout;

// 创建一个路由器实例
// 并且配置路由规则
let router = new VueRouter({
    mode: 'history',
    base: __dirname,
    routes: route
})


// 现在我们可以启动应用了！
// 路由器会创建一个 App 实例，并且挂载到选择符 #app 匹配的元素上。
const app = new Vue({
    router: router,
    render: h => h(App),
    watch:{
        "$route" : 'checkLogin'
    },
    created() {
        this.checkLogin();
    },
    methods:{
        checkLogin(){
            //检查是否存在登录的token
            if(!this.getCookie('token')){
                this.$router.push('/login');
            }else if(this.$route.path==="/login"){
                this.$router.push('/');
            }else{
                console.log(this.$route.path)
                this.$router.push(this.$route.path);
            }
        }
    }

}).$mount('#app')



